package com.buaa.aimall.userModule.Controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.buaa.aimall.Utils.BaseResponse;
import com.buaa.aimall.Utils.Enum.StatusCode;
import com.buaa.aimall.Utils.PageReturnResult;
import com.buaa.aimall.computeModule.Entity.ComputeEntity;
import com.buaa.aimall.computeModule.Service.ComputeService;
import com.buaa.aimall.goodsModule.Service.CollectService;
import com.buaa.aimall.modelModule.Entity.ModelEntity;
import com.buaa.aimall.modelModule.Service.ModelService;
import com.buaa.aimall.userModule.Converter.UserConvert;
import com.buaa.aimall.userModule.DTO.GetUserListDTO;
import com.buaa.aimall.userModule.DTO.PageDTO;
import com.buaa.aimall.userModule.VO.UserVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.buaa.aimall.userModule.DTO.HomepageContentRequestDTO;
import com.buaa.aimall.userModule.Service.UserService;
import com.buaa.aimall.userModule.Entity.UserEntity;

import jakarta.validation.Valid;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/user/statistic")
@CrossOrigin
public class UserStatisticController {

    @Autowired
    private ComputeService computeService;

    @Autowired
    private ModelService modelService;

    @Autowired
    private UserService userService;

    @Autowired
    private CollectService collectService;

    @PostMapping("/get-homepage-compute-content")
    public BaseResponse<PageReturnResult<ComputeEntity>> getHomepageContent(
            @RequestBody @Valid HomepageContentRequestDTO requestDTO) {
        try {
            PageReturnResult<ComputeEntity> computeList = computeService.getHomepageContent(
                    requestDTO.getOrderType(),
                    requestDTO.getCurrentPage(),
                    requestDTO.getPageSize(),
                    requestDTO.getName());

            // 这个接口可能由未登录的用户请求，所以无法获取当前用户，暂时先屏蔽掉返回商品是否收藏的功能

//            // 获取当前登录用户 ID
//            String userId = userService.getCurrentUser().getId();
//            // 用户收藏的 compute ID 集合
//            Set<String> collectedIds = collectService.getCollectedComputeIdsByUser(userId);
//            //原始对象引用，不是复制一份修改
//            for (ComputeEntity computeEntity : computeList.getRecords()) {
//                computeEntity.setIsCollected(collectedIds.contains(computeEntity.getId()));
//            }
            return new BaseResponse<>(StatusCode.SUCCESS, "查询成功", computeList);
        } catch (Exception e) {
            e.printStackTrace();
            return new BaseResponse<>(StatusCode.DAO_ERROR, "查询失败：" + e.toString(), null);
        }
    }

    @PostMapping("/get-homepage-model-content")
    public BaseResponse<PageReturnResult<ModelEntity>> getHomepageModelContent(
            @RequestBody @Valid HomepageContentRequestDTO requestDTO) {
        try {
            PageReturnResult<ModelEntity> modelList = modelService.getHomepageContent(
                    requestDTO.getOrderType(),
                    requestDTO.getCurrentPage(),
                    requestDTO.getPageSize(),
                    requestDTO.getName());

            return new BaseResponse<>(StatusCode.SUCCESS, "查询成功", modelList);
        } catch (Exception e) {
            return new BaseResponse<>(StatusCode.DAO_ERROR,
                    "查询失败：" + (e.getMessage() == null ? e.toString() : e.getMessage()), null);

        }
    }

    @GetMapping("/get-user-financial-info")
    public BaseResponse<Map<String, Integer>> getUserFinancialInfo() {
        try {
            UserEntity user = userService.getCurrentUser();
            Map<String, Integer> financialInfo = new HashMap<>();
            financialInfo.put("balance", user.getBalance());
            financialInfo.put("income", user.getIncome());
            return new BaseResponse<>(StatusCode.SUCCESS, "查询成功", financialInfo);
        } catch (Exception e) {
            return new BaseResponse<>(StatusCode.DAO_ERROR, "查询失败：" + e.getMessage(), null);
        }
    }

    @PostMapping("/user-list")
    public BaseResponse<PageReturnResult<UserVO>> getUserList(@RequestBody GetUserListDTO getUserListDTO) {
        Page<UserEntity> page = new Page<>(getUserListDTO.getCurrentPage(), getUserListDTO.getPageSize());

        QueryWrapper<UserEntity> queryWrapper = new QueryWrapper<>();
        if (getUserListDTO.getUsername() != null && !getUserListDTO.getUsername().trim().isEmpty()) {  // 假设PageDTO中有对应的getUsername方法
            queryWrapper.like("username", getUserListDTO.getUsername());
        }

        Page<UserEntity> entityPage = userService.page(page, queryWrapper);

        PageReturnResult<UserVO> result = new PageReturnResult<>();
        List<UserVO> voList = entityPage.getRecords().stream()
                .map(UserConvert.INSTANCE::userEntityToVO)
                .collect(Collectors.toList());
        result.setRecords(voList);
        result.setTotalCount(entityPage.getTotal());

        return new BaseResponse<>(StatusCode.SUCCESS, "获取系统内所有用户列表成功", result);
    }
}
